package com.pxl.springbootinit.controller;

import com.pxl.springbootinit.common.BaseResponse;
import com.pxl.springbootinit.common.ErrorCode;
import com.pxl.springbootinit.common.ResultUtils;
import com.pxl.springbootinit.exception.BusinessException;
import com.pxl.springbootinit.model.dto.file.UploadFileRequest;
import com.pxl.springbootinit.model.entity.User;
import com.pxl.springbootinit.service.UserService;
import com.pxl.springbootinit.utils.FileUploadUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Resource
    private UserService userService;

    @PostMapping("/upload")
    public BaseResponse<String> uploadImage(@RequestParam("file") MultipartFile file, UploadFileRequest uploadFileRequest,HttpServletRequest request) throws IOException {
        // 获取登录用户
        Long userId = uploadFileRequest.getId();
        if (userId == null){
            String filePath = FileUploadUtil.uploadFile(file, "admin",request);
            return ResultUtils.success(filePath);
        }
        User user = userService.getById(userId);
        if (user == null || user.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        try {
            // 调用工具类上传文件
            String filePath = FileUploadUtil.uploadFile(file, user.getId(),request);
            return ResultUtils.success(filePath);
        } catch (IOException e) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR , e.getMessage());
        }
    }
}
